//
//  ShoppingCartViewModel.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/4/20.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "ShoppingCartViewModel.h"
//vendor
#import "FMDBManager.h"
//untils
#import "ManagerGlobeUntil.h"
#import "NSString+Conversion.h"
#import "ManagerHttpBase.h"
#import "Global.h"
//model
#import "ShoppingCartSectionHeaderModel.h"
#import "ShoppingCartBottomModel.h"
@interface ShoppingCartViewModel()
@property(nonatomic, strong)NSMutableArray *dataSource;//存放商品数据
@end
@implementation ShoppingCartViewModel
- (instancetype)init {
    self = [super init];
    if (self) {
        _dataSource = [[NSMutableArray alloc]init];
        _sectionHeaderDatasArr = [[NSMutableArray alloc]init];
        _bottomModel = [[ShoppingCartBottomModel alloc]init];
    }
    return self;
}
#pragma mark -- 添加关注
- (void)markGoodsSuccess:(void (^)(NSString *successMsg))success failure:(void(^)(NSString *failureMessage))failureMessage {
    UserInfoModel *userInfoMode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableArray *goodsInfos =[[FMDBManager sharedManager]QueryIsChoosedDataWithShopID:[NSString stringISNull:xiaoQuAndStoreModel.storeID]];
    if (goodsInfos.count!=0) {
        NSMutableArray *goodsIDArr = [[NSMutableArray alloc]init];
        NSMutableArray *goodsTypeArr = [[NSMutableArray alloc]init];
        for (NSDictionary *goodDatas in goodsInfos) {
            NSString *goodID=[goodDatas objectForKey:@"ID"];
            NSString *isSelf=[goodDatas objectForKey:@"isProprietary"];
            [goodsIDArr addObject:goodID];
            [goodsTypeArr addObject:isSelf];
        }
        ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
        NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
        [parameter setObject:[NSString stringISNull:userInfoMode.token] forKey:@"TOKEN"];
        [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
        [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
        [parameter setObject:goodsIDArr.count == 0 ? @"" : [goodsIDArr componentsJoinedByString:@","] forKey:@"GOODSID"];
        [parameter setObject:goodsTypeArr.count == 0 ? @"" : [goodsTypeArr componentsJoinedByString:@","] forKey:@"ISSELF"];
        [manager parameters:parameter customPOST:@"user/doCollect" success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dataDic = (NSDictionary*)responseObject;
                NSString *msg = [dataDic objectForKey:@"MSG"];
                NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
                if ([state isEqualToString:@"0"]) {//请求成功
                    success(msg.length == 0 ? @"成功移入关注" : msg);
                } else {
                    failureMessage(msg.length == 0 ? @"移入关注失败" : msg);
                }
            }
        } failure:^(bool isFailure) {
            failureMessage(@"移入关注失败");
        }];
        
    } else{//还未选择商品
        failureMessage(@"您还没有选择商品");
    }
}
#pragma mark -- 根据选中cell来改变数据源
- (void)updateCellDataWithSelectedCellIndexPath:(NSIndexPath*)indexPath isSelected:(BOOL)isSelected success:(void (^)(NSArray * goodsData))success {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ShoppingCartSectionHeaderModel *headerModel = [self.sectionHeaderDatasArr objectAtIndex:indexPath.section];//sectionheader 信息
    NSDictionary *goodsInfo = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];//商品信息
    NSArray *handleDatasArr = nil;
    //便利店类型 1直营 0便利店
    NSString *isSelectedType = @"";
    if (headerModel.storeType == 1) {//1直营
        if (isSelected) {//选中
            isSelectedType = @"1";
        } else {//未选中
            isSelectedType = @"0";
        }
        //修改数据库自营商品选中
        [[FMDBManager sharedManager]modifyDataWithgoodID:[goodsInfo objectForKey:@"goodID"] ischoose:isSelectedType isProprietary:@"1"];
        //修改自营头部状态
        [self.sectionHeaderDatasArr replaceObjectAtIndex:indexPath.section withObject:[self handleSelfGoodsHeaderSeactionDatas:[self.dataSource objectAtIndex:indexPath.section]]];
        //获取修改后自营商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"];//查询购物车自营商品
    } else if (headerModel.storeType == 0) {//0便利店
        if (isSelected) {//选中
            isSelectedType = @"1";
        } else {//未选中
            isSelectedType = @"0";
        }
        //修改数据库便利店商品选中
         [[FMDBManager sharedManager]modifyDataWithshopID:mode.storeID goodID:[goodsInfo objectForKey:@"goodID"] ischoose:isSelectedType];
        //修改便利店头部状态
        [self.sectionHeaderDatasArr replaceObjectAtIndex:indexPath.section withObject:[self handleStoreGoodsHeaderSeactionDatas:[self.dataSource objectAtIndex:indexPath.section] storeID:mode.storeID]];
        //获取修改后便利店商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:mode.storeID];
    }
    //更新数据源信息
    [self.dataSource replaceObjectAtIndex:indexPath.section withObject:handleDatasArr];
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:mode.storeID];
    success(self.dataSource);
    
}
#pragma mark -- 根据是否选中sectionHeader来改变section数据
- (void)updateSectionDataWithSelectSectionHeaderWithGoodsType:(NSInteger)goodsType viewForHeaderInSection:(NSInteger)section isSelected:(BOOL)isSelected success:(void (^)(NSArray * goodsData))success {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ShoppingCartSectionHeaderModel *headerModel = [self.sectionHeaderDatasArr objectAtIndex:section];
    NSString *storeID=[NSString stringISNull:mode.storeID];
    NSArray *goodsArr = [self.dataSource objectAtIndex:section];
    NSArray *handleDatasArr = nil;
    //便利店类型 1直营 0便利店
    NSString *isSelectedType = @"";
    if (goodsType == 1) {//直营
        if (isSelected) {//选中
            isSelectedType = @"1";
        } else {//未选中
            isSelectedType = @"0";
        }
        for (NSDictionary *dataDic in goodsArr) {//修改自营商品选中状态
            [[FMDBManager sharedManager]modifyDataWithgoodID:[dataDic objectForKey:@"goodID"] ischoose:isSelectedType isProprietary:@"1"];
        }
        //重新获取自营商品信息
       handleDatasArr = [[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"];

    } else if(goodsType == 0) {//便利店
        if (isSelected) {//选中
            isSelectedType = @"1";
        } else {//未选中
            isSelectedType = @"0";
        }
        for (NSDictionary *dataDic in goodsArr) {//修改便利店商品选中状态
            [[FMDBManager sharedManager]modifyDataWithshopID:storeID goodID:[dataDic objectForKey:@"goodID"] ischoose:isSelectedType];
        }
         //重新获取便利店商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:storeID];
    }
    headerModel.isSelected = isSelected;//改变选中sectionheader 的状态
    //更新数据源信息
    [self.dataSource replaceObjectAtIndex:section withObject:handleDatasArr];
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:storeID];
    success(self.dataSource);
}

#pragma mark -- 选中所有商品
- (void)updateAllDataWithSelectedStatus:(BOOL)isSelected success:(void (^)(NSArray * goodsData))success {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *isSelectedType = @"";
    if (isSelected) {//全选
        isSelectedType = @"1";
    } else {//取消全选
        isSelectedType = @"0";
    }
    //对数据进行处理
    for (ShoppingCartSectionHeaderModel *headerModel in self.sectionHeaderDatasArr) {
        NSInteger sectionIndex = [self.sectionHeaderDatasArr indexOfObject:headerModel];
        NSArray *goodsInfo = [self.dataSource objectAtIndex:sectionIndex];
        for (NSDictionary *dataDic in goodsInfo) {
            if (headerModel.storeType == 1) {//自营
                 [[FMDBManager sharedManager]modifyDataWithgoodID:[dataDic objectForKey:@"goodID"] ischoose:isSelectedType isProprietary:@"1"];
            } else if (headerModel.storeType == 0) {//便利店
                 [[FMDBManager sharedManager]modifyDataWithshopID:mode.storeID goodID:[dataDic objectForKey:@"goodID"] ischoose:isSelectedType];
            }
        }
        //sectionheader选中状态
        headerModel.isSelected = [isSelectedType isEqualToString:@"1"] ? YES : NO;
    }
    //对处理后的数据进行重新组装
    for (ShoppingCartSectionHeaderModel *headerModel in self.sectionHeaderDatasArr) {
        NSInteger sectionIndex = [self.sectionHeaderDatasArr indexOfObject:headerModel];
        if (headerModel.storeType == 1) {//自营
            [self.dataSource replaceObjectAtIndex:sectionIndex withObject:[[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"]];
        } else if (headerModel.storeType == 0) {//便利店
            [self.dataSource replaceObjectAtIndex:sectionIndex withObject:[[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:mode.storeID]];
        }
    }
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:mode.storeID];
    success(self.dataSource);
    
}
#pragma mark -- 商品价格改变
- (void)updateCellDataWithSelectedCellIndexPath:(NSIndexPath *)indexPath goodsCount:(NSInteger)goodsCount success:(void (^)(NSArray *))success {
    NSString *goodsCountStr = [NSString stringWithFormat:@"%ld",(long)goodsCount];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ShoppingCartSectionHeaderModel *headerModel = [self.sectionHeaderDatasArr objectAtIndex:indexPath.section];//sectionheader 信息
    NSDictionary *goodsInfo = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];//商品信息
    NSArray *handleDatasArr = nil;
    //便利店类型 1直营 0便利店;
    if (headerModel.storeType == 1) {//1直营
        [[FMDBManager sharedManager]modifyDataWithgoodID:[goodsInfo objectForKey:@"goodID"] buynum:goodsCountStr isProprietary:@"1"];
        //重新获取自营商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"];
    } else if (headerModel.storeType == 0) {//0便利店
        [[FMDBManager sharedManager]modifyDataWithshopID:mode.storeID goodID:[goodsInfo objectForKey:@"goodID"] buynum:goodsCountStr];
        //重新获取便利店商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:mode.storeID];
    }
    //更新数据源信息
    [self.dataSource replaceObjectAtIndex:indexPath.section withObject:handleDatasArr];
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:mode.storeID];
    success(self.dataSource);

}
#pragma mark --  删除单个商品
- (void)deleteGoodsAtIndexPath:(NSIndexPath*)indexPath success:(void (^)(NSArray *goodsData))success {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ShoppingCartSectionHeaderModel *headerModel = [self.sectionHeaderDatasArr objectAtIndex:indexPath.section];//sectionheader 信息
    NSDictionary *goodsInfo = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];//商品信息
    NSArray *handleDatasArr = nil;
    NSMutableArray *sectionHeaderArr = [self.sectionHeaderDatasArr mutableCopy];
    NSMutableArray *datasource = [self.dataSource mutableCopy];
    //便利店类型 1直营 0便利店;
    if (headerModel.storeType == 1) {//1直营
        //自营单条删除
         [[FMDBManager sharedManager]deleteOneDataWithgoodID:[goodsInfo objectForKey:@"goodID"]];
        //重新获取自营商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"];
        if (handleDatasArr.count != 0) {
            [datasource replaceObjectAtIndex:indexPath.section withObject:handleDatasArr];
        } else {//自营商品只有一条
            [datasource removeObjectAtIndex:indexPath.section];
            [sectionHeaderArr removeObjectAtIndex:indexPath.section];
        }
    } else if (headerModel.storeType == 0) {//0便利店
        //便利店单条删除
        [[FMDBManager sharedManager]deleteOneDataWithShopID:mode.storeID goodID:[goodsInfo objectForKey:@"goodID"]];
        //重新获取便利店商品信息
        handleDatasArr = [[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:mode.storeID];
        if (handleDatasArr.count != 0) {
            [datasource replaceObjectAtIndex:indexPath.section withObject:handleDatasArr];
        } else {//便利店商品只有一条
            [datasource removeObjectAtIndex:indexPath.section];
            [sectionHeaderArr removeObjectAtIndex:indexPath.section];
        }
    }
    //更新数据源信息
    [self.sectionHeaderDatasArr removeAllObjects];
    [self.dataSource removeAllObjects];
    [self.sectionHeaderDatasArr addObjectsFromArray:[sectionHeaderArr copy]];
    [self.dataSource addObjectsFromArray:[datasource copy]];
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:mode.storeID];
    success(self.dataSource);
}
#pragma mark -- 多选删除
- (void)deleteSelectedGoodsSuccess:(void (^)(NSArray *goodsData))success {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    //对数据进行处理
    for (ShoppingCartSectionHeaderModel *headerModel in self.sectionHeaderDatasArr) {
        if (headerModel.storeType == 1) {//直营
            for (NSDictionary *dataDic in [[FMDBManager sharedManager]QueryisProprietaryIsChoosedData]) {//删除选中自营商品
                [[FMDBManager sharedManager]deleteOneDataWithgoodID:[dataDic objectForKey:@"ID"]];
            }
        } else if (headerModel.storeType == 0) {//便利店
            for (NSDictionary *dataDic in [[FMDBManager sharedManager]QueryIsChoosedDataInShopWithShopID:mode.storeID]) {//删除选中便利店商品
                [[FMDBManager sharedManager]deleteOneDataWithShopID:mode.storeID goodID:[dataDic objectForKey:@"ID"]];
            }
        }
    }
    //从数据库查所有数据，包括自营和便利店商品
    NSArray *goodsDatas= [[FMDBManager sharedManager]QueryDataWithshopID:mode.storeID];
    [self handleShoppingCartDatas:goodsDatas storeID:mode.storeID];
    success(self.dataSource);
}
#pragma mark -- 获取购物车数据
- (void)requestShoppingCartDatas:(void (^)(NSArray * goodsData))shoppingCartDataBlock {
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSString *storeID=[NSString stringISNull:mode.storeID];
    //从数据库查所有数据，包括自营和便利店商品
    NSArray *goodsDatas= [[FMDBManager sharedManager]QueryDataWithshopID:storeID];
    shoppingCartDataBlock([self handleShoppingCartDatas:goodsDatas storeID:storeID]);
}
#pragma mark -- 处理从数据库请求的数据
- (NSArray*)handleShoppingCartDatas:(NSArray*)arr storeID:(NSString*)storeID{
    [self.sectionHeaderDatasArr removeAllObjects];
    NSArray *goodsDataArr = nil;
    //查询自营商品 添加进数据源
    NSArray *selfGoodsDatas = [[FMDBManager sharedManager]QueryDataWithIsProprietary:@"1"];
    //查询便利店商品 添加进数据源
    NSArray *storeGoodsDatas = [[FMDBManager sharedManager]QueryIsNoProprietaryDataWithShopID:storeID];
    if (selfGoodsDatas.count != 0 && storeGoodsDatas.count != 0) {//购物车包含便利店和自营商品
        //判断最后添加的商品是自营商品还是便利店商品
        NSDictionary *dic =[arr firstObject];
        BOOL isSelfGoods = [self judgeIsSelfGoodsWithGoods:[dic objectForKey:@"isProprietary"]];
        if (isSelfGoods) {//自营商品在上面
            goodsDataArr = @[selfGoodsDatas,storeGoodsDatas];
            [self.sectionHeaderDatasArr addObject:[self handleSelfGoodsHeaderSeactionDatas:selfGoodsDatas]];
            [self.sectionHeaderDatasArr addObject:[self handleStoreGoodsHeaderSeactionDatas:storeGoodsDatas storeID:storeID]];
            
        }else {//便利店商品在上面
             goodsDataArr = @[storeGoodsDatas,selfGoodsDatas];
            [self.sectionHeaderDatasArr addObject:[self handleStoreGoodsHeaderSeactionDatas:storeGoodsDatas storeID:storeID]];
            [self.sectionHeaderDatasArr addObject:[self handleSelfGoodsHeaderSeactionDatas:selfGoodsDatas]];
        }
        
    } else if (selfGoodsDatas.count != 0) {//只包含自营商品
         goodsDataArr = @[selfGoodsDatas];
         [self.sectionHeaderDatasArr addObject:[self handleSelfGoodsHeaderSeactionDatas:selfGoodsDatas]];
    } else if (storeGoodsDatas.count != 0) {//只包含便利店商品
         goodsDataArr = @[storeGoodsDatas];
         [self.sectionHeaderDatasArr addObject:[self handleStoreGoodsHeaderSeactionDatas:storeGoodsDatas storeID:storeID]];
    }
    //计算总价格
    [self calculationSelectedGoodsPriceWithStoreID:storeID];
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:goodsDataArr];
    return goodsDataArr;
}
#pragma mark -- 判断是否是自营商品
- (BOOL)judgeIsSelfGoodsWithGoods:(NSString*)goods {
    if ([goods isEqualToString:@"1"]) {
        return YES;
    } else {
        return NO;
    }
}
#pragma mark -- 处理自营商品section的头部数据
- (ShoppingCartSectionHeaderModel*)handleSelfGoodsHeaderSeactionDatas:(NSArray*)selfGoodsDatas {
    ShoppingCartSectionHeaderModel *sectionHeaderModel = [[ShoppingCartSectionHeaderModel alloc]init];
    sectionHeaderModel.storeType = 1;
    NSArray *selectdSeftGoodsArr = [[FMDBManager sharedManager]QueryisProprietaryIsChoosedData];
    if (selectdSeftGoodsArr.count == selfGoodsDatas.count) {
        sectionHeaderModel.isSelected = YES;
    } else {
        sectionHeaderModel.isSelected = NO;
    }
    sectionHeaderModel.title = kDaShiHuiStoreName;
    return sectionHeaderModel;
}
#pragma mark -- 处理便利店商品section的头部数据
- (ShoppingCartSectionHeaderModel*)handleStoreGoodsHeaderSeactionDatas:(NSArray*)storeGoodsDatas storeID:(NSString*)storeID{
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ShoppingCartSectionHeaderModel *sectionHeaderModel = [[ShoppingCartSectionHeaderModel alloc]init];
    sectionHeaderModel.storeType = 0;
    NSArray *selectedStoreGoodsArr = [[FMDBManager sharedManager]QueryIsChoosedDataInShopWithShopID:storeID];
    if (selectedStoreGoodsArr.count == storeGoodsDatas.count) {
        sectionHeaderModel.isSelected = YES;
    } else {
        sectionHeaderModel.isSelected = NO;
    }
    sectionHeaderModel.title = mode.storeName;
    return sectionHeaderModel;
}

#pragma mark -- 计算选择商品的总价格
-(void)calculationSelectedGoodsPriceWithStoreID:(NSString*)storeID {
    NSArray *goodsDatas= [[FMDBManager sharedManager]QueryDataWithshopID:storeID];
    NSArray *selectedGoodsDatas = [[FMDBManager sharedManager]QueryIsChoosedDataWithShopID:storeID];
    if (goodsDatas.count != 0 && goodsDatas.count == selectedGoodsDatas.count) {//如果选中商品和所有商品数量相同，就表面全选
        self.bottomModel.isSelected = YES;
    } else {
        self.bottomModel.isSelected =  NO;
    }
    CGFloat totalPrice = 0;
    NSInteger selectedGoodsCount = 0;
    for (NSDictionary *dataDic in selectedGoodsDatas) {//计算总价格
        totalPrice += [[dataDic objectForKey:@"SELLPRICE"] floatValue]*[[dataDic objectForKey:@"BUYNUM"]integerValue];
        selectedGoodsCount += [[dataDic objectForKey:@"BUYNUM"]integerValue];
    }
    self.bottomModel.totalPrice = [NSString stringWithFormat:@"%.2f",totalPrice];
    self.bottomModel.goodsCount = [NSString stringWithFormat:@"%ld",(long)selectedGoodsCount];
}
@end
